import Container from "typedi";
import { Metadata } from "@grpc/grpc-js";
import { Token } from "typedi";
import { Err, RES } from "client/configVo";
import { getRedis } from "./redis";
import { CLIENT_ID } from "./config";
import { logger } from "@vendor/logger";

interface requestHeadersEntity {
  [key: string]: string;
}

// 域名
export const X_BIZCTX_DOMAIN = new Token("X_BIZCTX_DOMAIN");

// 语言
export const X_BIZCTX_LANGUAGE = new Token("X_BIZCTX_LANGUAGE");

// 模版
export const X_BIZCTX_LAYOUT = new Token("X_BIZCTX_LAYOUT");

// countryCode
export const X_BIZCTX_CC = new Token("X_BIZCTX_CC");

// countryName
export const X_BIZCTX_COUNTRY = new Token("X_BIZCTX_COUNTRY");

// province
export const X_BIZCTX_STATE = new Token("X_BIZCTX_STATE");

// city
export const X_BIZCTX_CITY = new Token("X_BIZCTX_CITY");

// currency
export const X_BIZCTX_CURRENCY = new Token("X_BIZCTX_CURRENCY");

// userid
export const X_BIZCTX_UID = new Token("x-bizctx-uid");

// UA
export const USER_AGENT = new Token("USER_AGENT");

// 全局headers
export const USER_HEADERS = new Token("USER_HEADERS");

// 原始链接
export const ORIGINAL_URL = new Token("ORIGINAL_URL");

export const USER_COOKIE = new Token("USER_COOKIE");

// 获取ip
export const getIp = (req: any) => {
  const ip =
    req.headers?.["x-forwarded-for"] ||
    req.ip ||
    req.connection?.remoteAddress ||
    req.socket?.remoteAddress ||
    req.connection?.socket?.remoteAddress ||
    "";
  return ip;
};

// 设置请求头
export const setReqHeader = (userInfo: any) => {
  const meta = new Metadata();
  meta.set("x-client-id", CLIENT_ID);
  meta.set("x-user-id", userInfo.id);
  meta.set("x-user-group", userInfo.id);
  meta.set("x-bizctx-uid", userInfo.id);
  meta.set("x-bizctx-ip", userInfo.ip);
  return meta;
};

// token失效信息
export const TOKEN_INFO = (opts?: any): RES => {
  const { msg = "token失效" } = opts || {};
  return {
    no: -1,
    msg,
  };
};

// 封装公共成功信息
export const RES_INFO = (opts: any): RES => {
  const { data } = opts;
  return {
    no: 0,
    msg: "成功",
    data,
  };
};

// 封装公共错误信息
export const ERR_INFO = (opts: any): Err => {
  const { msg } = opts;
  return {
    no: 1,
    msg,
  };
};

// 统一处理接口错误
export const REPO_ERR = (err: any, url: String) => {
  logger.error(`${url}：${err}`);
  return ERR_INFO({ msg: err?.details || err });
};

// 统一处理登录相关错误
export const REPO_TOKEN = (err: any, url: String) => {
  logger.error(`${url}：${err}`);
  return TOKEN_INFO({ msg: err?.details || err });
};

// 统一处理Promise.all是否有错误数据
export const ERR_ALL_PROMISE = (resList: any) => {
  resList = resList || [];
  for (let i = 0; i < resList.length; i++) {
    const res = resList[i];
    if (res.no !== 0) {
      return res;
    }
  }
  return false;
};

// 拿到token
export const getToken = (request: any) => {
  return request.headers.authorization?.split("Bearer ")?.[1];
};

// token判断
export const VALID_TOKEN = (opts: any) => {
  const { request, response } = opts;
  return new Promise(async (resolve, reject) => {
    try {
      const token = getToken(request);
      const data: any = await getRedis(token);
      if (data) {
        resolve(JSON.parse(data));
      } else {
        response.send(TOKEN_INFO({ msg: `token已过期` }));
      }
    } catch (err) {
      response.send(TOKEN_INFO({ msg: `redis获取token失败：${err}` }));
    }
  });
};

// 权限
export const PERMISSIONS = {
  zdlb: "shop_list_all", // 店铺列表
  splb: "product_list_all", // 商品列表
  khgl: "", // 客户管理-待定
  zkgl: "", // 折扣管理-待定
  yxgl: "", // 营销管理-待定
  sjzx: "", // 数据中心-待定
};
